package com.example.servlet;

import com.example.DAO.DBUtilsDAO;
import com.example.DAO.impl.DBUtilsFactory;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet({"/register"})
public class RegisterServlet extends HttpServlet {
    private DBUtilsDAO dbConnection = DBUtilsFactory.getDBConnection();

    public RegisterServlet() {
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String usernameFromIndex = req.getParameter("username1");
        String passwordFromIndex = req.getParameter("password1");
        String otherPasswordFromIndex = req.getParameter("password2");
        String warn = null;
        if (!usernameFromIndex.isEmpty() && !passwordFromIndex.isEmpty() && !otherPasswordFromIndex.isEmpty()) {
            if (!passwordFromIndex.equals(otherPasswordFromIndex)) {
                warn = "当前输入的密码与确认密码不相同，请重新输入";
            }
        } else {
            warn = "请将未填字段补全";
        }

        if (warn != null) {
            req.setAttribute("warn", warn);
            req.getRequestDispatcher("/register.jsp").forward(req, resp);
        } else {
            String sql = "INSERT INTO user (user_name, user_password, identity, head_image) VALUES (?, ?, ?, ?)";

            try {
                try (
                        Connection conn = this.dbConnection.getConnection();
                        PreparedStatement prepInsert = conn.prepareStatement(sql);
                ) {
                    prepInsert.setString(1, usernameFromIndex);
                    prepInsert.setString(2, passwordFromIndex);
                    prepInsert.setString(3, "客户");
                    prepInsert.setString(4, "image/Customer.jpg");
                    int affectedRows = prepInsert.executeUpdate();
                    if (affectedRows > 0) {
                        resp.sendRedirect("login.jsp");
                    } else {
                        req.setAttribute("warn", "用户注册失败，请稍后再试");
                        req.getRequestDispatcher("/register.jsp").forward(req, resp);
                    }
                }

            } catch (SQLException e) {
                throw new RuntimeException("插入数据失败", e);
            }
        }
    }
}
